#!/bin/sh

echo "Usage: $0 [-daemon]"

BASE_DIR=$(dirname $0)
BASE_DIR=$(cd ${BASE_DIR}; pwd)

if [ -f "${BASE_DIR}/env.sh" ]; then
  . "${BASE_DIR}/env.sh"
fi

if [ -z "$JAVA_HOME" ]; then
  JAVA="$(which java)"
else
  JAVA="$JAVA_HOME/bin/java"
fi

APP_OPTS="-Dapp.dir=${BASE_DIR}"

LOG4J_CONFIG_FILE=$(find ${BASE_DIR} -name "log4j.properties")
LOG4J_OPTS="-Dlog4j.properties=${LOG4J_CONFIG_FILE}"

JAVA_OPTS="${APP_OPTS} ${LOG4J_OPTS} ${JAVA_OPTS}"

echo "Use JAVA      = ${JAVA}"
echo "Use JAVA_OPTS = ${JAVA_OPTS}"

APP_JAR="${BASE_DIR}/spring-boot-app-0.1.jar"
APP_LOG="${BASE_DIR}/logs/app.out"

echo "Use APP_JAR   = ${APP_JAR}"

COMMAND=$1
case $COMMAND in 
  -daemon)
    DAEMON=true
    shift
    ;;
  *)
    ;;
esac

if [ "x$DAEMON" == "xtrue" ]; then
  nohup ${JAVA} ${JAVA_OPTS} -jar ${APP_JAR} "$@" > "$APP_LOG" 2>&1 < /dev/null &
else
  exec ${JAVA} ${JAVA_OPTS} -jar ${APP_JAR} "$@"
fi
